﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain;
using SapaFinance.Domain.Model;
using SapaFinance.GenericRepository;
using SapaFinance.Infrastructure;

namespace SapaFinance.Services
{
    public interface IBankService
    {
        IEnumerable<AbstractDTO> GetListDTO();
        IEnumerable<SelectListItem> GetSelectedListById(Guid id);
        void Insert(BankDTO dto);
        void Delete(Guid id);
        void Update(BankDTO dto);
    }

    public class BankService : IBankService
    {
        private readonly IGenericRepository<Bank, Guid> _bankRepository;
        private readonly IMappingEngine _mappingEngine;
        private readonly IEntityFactory _entityFactory;
        private readonly IUnitOfWork _unitOfWork;

        public BankService(IGenericRepository<Bank, Guid> bankRepository, IUnitOfWork unitOfWork, IMappingEngine mappingEngine, IEntityFactory entityFactory)
        {
            _bankRepository = bankRepository;
            _unitOfWork = unitOfWork;
            _mappingEngine = mappingEngine;
            _entityFactory = entityFactory;
        }

        public IUserService UserService { get; set; }
        #region IBankService Members

        public IEnumerable<AbstractDTO> GetListDTO()
        {
            return _mappingEngine.Map<IEnumerable<Bank>, IEnumerable<BankDTO>>(_bankRepository.GetAll());
        }

        public IEnumerable<SelectListItem> GetSelectedListById(Guid id)
        {
            return Guid.Empty.Equals(id)
                       ? _mappingEngine.Map<IEnumerable<Bank>, List<SelectListItem>>(_bankRepository.GetAll())
                       : _mappingEngine.Map<Bank, IEnumerable<SelectListItem>>(_bankRepository.GetById(id));
        }

        public void Insert(BankDTO dto)
        {
            var entity = _entityFactory.BuildBank(dto);
            _bankRepository.Insert(entity);
            _unitOfWork.Flush();
        }

        public void Delete(Guid id)
        {
            var entity = _bankRepository.GetById(id);
            _bankRepository.Delete(entity);
            _unitOfWork.Flush();
        }
       

        public void Update(BankDTO dto)
        {
            var user = UserService.GetUser(dto.CurrentUser);
            var entity = _bankRepository.GetById(dto.UID);
            if (user != null){
                entity.Bin = dto.Bin;
                entity.CorrespondentAccount = dto.CorrespondentAccount;
                entity.Name = dto.Name;
                entity.Swift = dto.Swift;
                entity.Address = dto.Address;
                entity.City = dto.City;
                entity.IsHidden = dto.IsHidden;
                entity.Change(user);
                _bankRepository.Update(entity);
                _unitOfWork.Flush();
            }
        }

        #endregion
    }
}